package org.example.utils.post.comment;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.dao.dao.post.PReplyDao;
import org.example.dao.dao.user.UUserDao;
import org.example.dao.dto.commom.UserInfo;
import org.example.dao.dto.post.PCommentDto;
import org.example.dao.entity.post.PComment;
import org.example.dao.entity.post.PReply;
import org.example.dao.entity.user.UUser;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class ExtendCommentService {

    @Resource
    private PReplyDao pReplyDao;

    @Resource
    private UUserDao uUserDao;

    @Resource
    private RedisCommentService redisCommentService;

    public IPage<PCommentDto> getPCommentDtoIpage(IPage<PComment> pPosts) {
        List<PCommentDto> list = new ArrayList<>();
        for (PComment comment : pPosts.getRecords()) {
            PCommentDto commentDto = createCommentDto(comment);
            list.add(commentDto);
        }
        IPage<PCommentDto> iPage = new Page<>();
        iPage.setRecords(list);
        iPage.setTotal(pPosts.getTotal());
        iPage.setPages(pPosts.getPages());
        iPage.setCurrent(pPosts.getCurrent());
        iPage.setSize(pPosts.getSize());
        return iPage;
    }

    public PCommentDto createCommentDto(PComment comment){

        PCommentDto commentDto = new PCommentDto();

        redisCommentService.getCommentCache(comment);

        commentDto.setPComment(comment);
        Long userPostId = comment.getUserId();
        UUser user = uUserDao.selectById(userPostId);
        UserInfo userInfo = new UserInfo(user);
        commentDto.setUserInfo(userInfo);
        Long commentId = comment.getId();
        commentDto.setIsLike(redisCommentService.judgeIsMember(commentId.toString(),userPostId.toString()));

        LambdaQueryWrapper<PReply> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(PReply::getCommentId, comment.getId());
        List<PReply> list1 = pReplyDao.selectList(lambdaQueryWrapper2);
        if (list1 == null || list1.size() == 0) {
            commentDto.setHasReply(false);
        } else {
            commentDto.setHasReply(true);
        }

        return commentDto;
    }


    public LambdaQueryWrapper<PComment> getLambdaQueryWrapper() {
        LambdaQueryWrapper<PComment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PComment::getIsValid, 1);
        lambdaQueryWrapper.orderBy(true, false, PComment::getCreateTime);
        return lambdaQueryWrapper;
    }


}
